#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import sys
import time
import re
import tweepy
import model_handling as mh 
import datetime
import logging

def Parse(vtrig,text):
    ss = {}
    r=re.compile('(%s)(.*?)(:\)|:\()' %vtrig)
    wl = re.findall(r,text)
    for w in wl:
        if len(w) == 3:
            vt = w[0]
            ws = w[1]
            sent = w[2]
        else:
            logging.error("Text %s extraction error" %text)

        ss[ws] = sent
        for s in ws.split(" "):
            if s.startswith('@') or s.startswith('#') or s.startswith('http//:'):
                ss[s] = sent
    return ss

def Search(tag,rpp=100):
    sentiments = {":)":True,":(":False}
    mlid = mh.GetLastVoteMsgId()
    if not mlid:
        mlid = 0
    logging.info("Twitter searching from %d ....." %mlid)
    srs = []
    for p in range(1,16):
        try:
            srq = tweepy.api.search(q=tag,rpp=rpp,page=p,since_id=mlid)
        except Exception,e:
            logging.error("Error %s" %e)
        if srq:
            srs += srq
        else:
            break
    if not srs:
        logging.warning("No search results")
        return
    logging.info("Twitter searching finished")
    
    logging.info("Parsing %d votes" %len(srs))
    xid = 0
    srs.reverse()
    for sr in srs:
        logging.info("Vote mid %d" %sr.id)
        try:
            sender = sr.from_user
            ss = Parse(tag,sr.text)
            for w,s in ss.items():
                mh.AddSOVote(sr.id,sender,w,sentiments[s])
        except Exception,e:
            logging.error("Error %s" %e)
            break

    logging.info("%d votes parsed" %len(srs))

from random import choice
def ComparisonResults(d):
    votes = {}
    for v,u in d.items():
        votes[v] = [0,0]
    for v,u in d.items():
        for i,s in u.items():
            if s == ":)":
                votes[v][0] += 1
            if s == ":(":
                votes[v][1] += 1
    return votes

def TestVector():
    u = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']
    sent = [':)',':(']
    test_twitts = []
    results = {}
    for i in range(100):
        uid = '@' + choice(u)
        vid = '@' + choice(u)
        vh = '#' + choice(u)
        s = choice(sent)
        t = [uid,'Out text #s In text with %s and %s sentiment %s out text' %(vid,vh,s)]
        if results.has_key(vid):
            results[vid][uid] = s
        else:
            results[vid] = {uid:s}
        if results.has_key(vh):
            results[vh][uid] = s
        else:
            results[vh] = {uid:s}
        tt = t[1].split(":")[0].strip()
        if results.has_key(tt):
            results[tt][uid] = s
        else:
            results[tt] = {uid:s}
        test_twitts.append(t)
#    for c,v in ComparisonResults(results).items():
#        logging.info("%s %s" %(c,v))
    return test_twitts

def TestSearch(tag):
    sentiments = {":)":True,":(":False}
    t = TestVector()
    logging.info("Parsing %d votes" %len(t))
    for ti in t:
        try:
            sender = ti[0]
            ss = Parse(tag,ti[1])
            for w,s in ss.items():
                logging.info("vote parsing")
                mh.AddSOVote(0,sender,w,sentiments[s])
                logging.info("vote parsed")
        except Exception,e:
            logging.error("Error %s" %e)
            break
    logging.info("%d votes parsed" %len(t))
        
